/*
 * @Author: hongbin
 * @Date: 2022-12-24 20:31:26
 * @LastEditors: hongbin
 * @LastEditTime: 2022-12-24 20:40:58
 * @Description:
 */
import { post } from "../../../api";
import { useAuth } from "../../../context/AuthProvide";
import { SocketManager } from "../../../socket";

/**
 * 确定添加对方为好友的hook
 * 不将其写成函数是为了直接操作 useAuth 更改状态
 */
const useAddFriendHook = () => {
    const { user, recordUserInformation } = useAuth();

    const fn = async (other: string, callback?: (success: boolean) => void) => {
        const { data } = await post("/FriendsList/add", { self: user._id, other });
        if (!data) {
            callback && callback(false);
            return console.error("加好友失败！");
        }
        console.log("双方添加好友：", data);
        SocketManager.emit("agreeAddFriend", {
            self: user._id,
            selfName: user.name,
            other,
            chatRecordId: data.chatRecordId,
        });
        const newInfo = {
            ...user,
            friendsList: [...user.friendsList!, { date: data.date, friendId: other, chatRecordId: data.chatRecordId }],
        };
        recordUserInformation(newInfo);
        callback && callback(true);
    };

    return fn;
};

export default useAddFriendHook;
